<template>
    <view class="content">
        <show-modal></show-modal>
        <!-- <cu-custom bgColor="bg-gradual-red" :isClose="true" @customClosePage="customClosePage">
            <block slot="backText">关闭</block>
            <block slot="content">发布作品</block>
        </cu-custom> -->
        <form v-if="step == 1">
            <view class="cu-form-group margin-top dashed-bottom">
                <input placeholder="填写菜谱名称" class="text-xl-important text-center text-bold"
                    v-model="formData.name"></input>
            </view>
            <view class="bg-white padding-xs flex align-center">
                <view class="flex-sub">
                    <view class="padding">
                        <text class="margin-right-xs">
                            提示：
                            1.好的标题是吸引关注的第一步。
                            2.在标题中描述菜谱的特点，会吸引更多用户点击。
                            &nbsp;&nbsp;如[补锌的糯米饭团]、[软嫩的手指虾条]
                        </text>
                    </view>
                </view>
            </view>
            <view class="bg-white padding flex flex-direction">
                <button class="cu-btn margin-tb-sm lg" :class="formData.name.trim().length>0?'bg-red':'bg-gray'"
                    :disabled="formData.name.trim().length>0?false:true" @click="nextStep">下一步</button>
            </view>
        </form>
        <form v-if="step == 2">
            <view class="cu-form-group no-border" style="padding: 0upx; min-height: 0upx;">
                <view class="grid col-1 flex-sub">
                    <view style="padding-bottom: auto; position: relative;" @tap="viewImage"
                        v-if="formData.pic.length>0||formData.video.length>0">
                        <image style="width: 100%;" :src="formData.pic" mode="widthFix" v-if="formData.pic.length>0">
                        </image>
                        <video style="width: 100%;" :src="formData.video" mode="widthFix" v-if="formData.video.length>0"
                            :poster="formData.video + '?x-oss-process=video/snapshot,t_0000,f_jpg'"></video>

                        <view class="tag-close" @tap.stop="delImg">
                            <text class='cuIcon-close'></text>
                        </view>
                    </view>
                    <view class="bg-gray"
                        style="margin: 0upx; padding-bottom: 100%;position: relative; overflow: hidden;"
                        @tap="chooseImage" v-if="formData.pic.length==0&&formData.video.length==0">
                        <text class='cuIcon-cameraadd text-tips-main'>菜谱封面(或2分钟小视频)</text>
                        <text class='cuIcon- text-tips-sub'>诱人的封面图是吸引查看的关键</text>
                    </view>
                </view>
            </view>
            <view class="cu-form-group no-border dashed-bottom">
                <input placeholder="填写菜谱名称" class="text-xl-important text-center text-bold"
                    v-model="formData.name"></input>
            </view>
            <view class="cu-form-group no-border">
                <textarea maxlength="-1" placeholder="输入这道美食背后的故事或温馨提示" v-model="formData.description"></textarea>
            </view>

            <view class="cu-form-group margin-top">
                <view class="title action block">
                    <text class="cuIcon-titles text-red"></text> 月龄
                </view>
                <picker @change="pickerChangeMonth" :value="indexMonth" :range="pickerMonth">
                    <view class="picker">
                        {{
                            indexMonth>-1?pickerMonth[indexMonth]:(formData.listMonth.length > 0?formData.listMonth[0].cateName:'请选择合适的阶段')
                        }}
                    </view>
                </picker>
            </view>
            <view class="cu-form-group">
                <view class="title action block">
                    <text class="cuIcon-titles text-red"></text> 用料
                </view>
            </view>
            <view class="bg-white padding-xs flex flex-direction">
                <view class="flex-direction margin-left margin-bottom-sm text-sm">
                    <text class="text-gray block">猜你可能想要用到</text>
                </view>
                <view class="flex-direction margin-left-sm">
                    <button class="cu-btn sm margin-right" @click="addMaterial('面粉')">面粉</button>
                    <button class="cu-btn sm margin-right" @click="addMaterial('鸡蛋')">鸡蛋</button>
                    <button class="cu-btn sm margin-right" @click="addMaterial('盐巴')">盐巴</button>
                </view>
                <view class="cu-form-group" v-for="(item,index) in formData.listMaterial">
                    <text class="flex-sub cuIcon-deletefill text-red margin-right" v-if="isEdit" @click="onRemove(item)"></text>
                    <view style="display: block;">
                        <input class="flex-sub text-sm-black" placeholder="食材:如鸡蛋" v-model="item.name"></input>
                        <input class="flex-sub text-sm-black" placeholder="用量:如1个" v-model="item.quantity"></input>
                    </view>
                    <picker class="flex-sub text-sm-black" @change="pickerChangeUnit($event, index)"
                        :value="item.indexUnit" :range="pickerUnit">
                        <view class="picker">
                            {{item.indexUnit>-1?pickerUnit[item.indexUnit]:(item.unit?item.unit:'单位')}}
                        </view>
                    </picker>
                </view>
                <view class="cu-form-group">
                    <button class='cu-btn bg-transparent text-s margin-0 padding-0 text-red'
                        @click="onAdd">增加一行</button>
                    <button class='cu-btn bg-transparent text-s margin-0 padding-0 text-red' @click="onEdit">调整</button>
                </view>
            </view>

            <view class="cu-form-group margin-top">
                <view class="title action block">
                    <text class="cuIcon-titles text-red"></text> 做法
                </view>
                <button class='action block cu-btn bg-transparent text-s margin-0 padding-0 text-red'
                    @click="chooseImageMultiple">批量传图</button>
            </view>

            <view class="bg-white padding-xs flex align-center" v-for="(item,index) in formData.listStep" :key="index">
                <view class="flex-sub">
                    <view class="text-xl padding">
                        <text class="text-black text-bold">
                            步骤 {{index + 1}}
                        </text>
                        <text class="text-gray"> / {{formData.listStep.length}}</text>
                    </view>

                    <view class="cu-card dynamic no-card">
                        <view class="cu-item shadow">
                            <view class="padding">
                                <input placeholder="添加步骤说明" v-model="item.description"></input>
                            </view>
                            <view class="grid flex-sub padding" style="position: relative;">
                                <image style="width: 100%;" :src="item.imageUrl" mode="widthFix"></image>

                                <view class="tag-close" style="right: 15px; top: 15px;" @tap.stop="delStep(item)">
                                    <text class='cuIcon-close'></text>
                                </view>
                            </view>
                        </view>
                    </view>
                </view>
            </view>

            <view class="cu-form-group margin-top">
                <view class="title action block">
                    种类
                </view>
                <picker @change="pickerChangeType" :value="indexType" :range="pickerType">
                    <view class="picker">
                        {{indexType>-1?pickerType[indexType]:(formData.listType.length > 0?formData.listType[0].cateName:'请选择种类')}}
                    </view>
                </picker>
            </view>
            <view class="cu-form-group">
                <view class="title action block">
                    制作方法
                </view>
                <picker @change="pickerChangeMake" :value="indexMake" :range="pickerMake">
                    <view class="picker">
                        {{indexMake>-1?pickerMake[indexMake]:(formData.listMake.length > 0?formData.listMake[0].cateName:'请选择制作方法')}}
                    </view>
                </picker>
            </view>
            <view class="bg-white padding flex flex-direction margin-top">
                <button class="cu-btn margin-tb-sm lg" :class="formData.name.trim().length>0?'bg-red':'bg-gray'"
                    @click="submit">发布这个菜谱</button>
            </view>
        </form>
    </view>
</template>
<script>
    export default {
        data() {
            return {
                step: 1,
                isEdit: false,
                pickerUnit: ['克', '两', '斤', '勺', '碗', '根', '片', '个', '少许', '适量'],
                indexUnit: -1,
                pickerMonth: ['6月龄', '7月龄', '8月龄', '9月龄', '10月龄', '11月龄', '12月龄', '18月龄', '24月龄'],
                indexMonth: -1,
                pickerType: ['饭粥', '面条', '泥糊', '糕点', '烫羹', '小饼', '丸子香肠', '其他'],
                indexType: -1,
                pickerMake: ['蒸', '炒', '煎', '搅拌', '煮', '烘培', '炖', '其他'],
                indexMake: -1,
                formData: {
                    id: null,
                    name: "",
                    description: "",
                    pic: "",
                    video: "", //https://jzy-sup3-dev.oss-cn-shanghai.aliyuncs.com/chik/video/73b58770efee46b09b73cc9552484ad1_2619588c1b02e5315700092132a67fd7.mp4
                    listMaterial: [],
                    listMonth: [],
                    listType: [],
                    listMake: [],
                    listStep: [],
                }
            }
        },
        mounted(e) {
            console.log("mounted 获取草稿", e)
        },
        onLoad(e) {
            console.log("onLoad 获取草稿", e)
            if (e.id) {
                this.formData.id = e.id;
                this.getDetail();
            }

            let that = this;
            uni.checkSession({
                success: function(t) {
                    console.log("没过期");
                },
                fail: function() {
                    console.log("过期了");
                    uni.showLoading({
                        mask: true,
                        title: '授权登录中...',
                    })
                    let baseAuthCode = uni.getStorageSync("baseAuthCode");
                    if (!baseAuthCode) {
                        that.$api.baseToken().then(() => {
                            uni.hideLoading();
                        });
                        return;
                    }
                    that.$api.baseLogin(baseAuthCode).then(() => {
                        uni.hideLoading();
                    });
                }
            });
        },
        methods: {
            getDetail() {
                let data = {
                    "bookId": this.formData.id
                }
                this.$api.bookDetail(data).then((res) => {
                    console.log("请求详情成功", JSON.stringify(res.data));
                    this.formData = res.data;
                    this.step = 2;
                }).catch((err) => {
                    console.error('request fail', err);
                })
            },
            customClosePage() {
                console.log("关闭页面");
                if (!this.formData.name && !this.formData.pic && !this.formData.video && this.formData.listStep
                    .length == 0) {
                    uni.navigateBack({
                        delta: 1
                    });
                    return false;
                }
                this.$showModal({
                    content: '是否保存到草稿箱？',
                    confirmText: "保存草稿",
                    cancelText: "放弃编辑",
                    success: (res) => {
                        if (res.confirm) {
                            console.log('用户点击确定');
                            // 保存到草稿，保存成功后，退出
                            this.formData.auditStatus = 1;
                            this.$api.saveBook(this.formData).then((res) => {
                                uni.navigateBack({
                                    delta: 1
                                });
                            }).catch((err) => {
                                console.error('request fail', err);
                                uni.showToast({
                                    title: "保存草稿失败",
                                    icon: "none"
                                })
                            })
                        } else if (res.cancel) {
                            console.log('用户点击取消');
                            uni.navigateBack({
                                delta: 1
                            });
                        }
                    }
                });
                return true;
            },
            nextStep() {
                console.log("name", this.formData.name.trim().length);
                this.step = 2;
            },
            chooseImage() {
                let isCanUseMedia = true;

                // #ifdef  MP-TOUTIAO
                isCanUseMedia = tt.canIUse("chooseMedia");
                console.log("canUse", isCanUseMedia);
                // #endif

                if (isCanUseMedia) {
                    uni.chooseMedia({
                        count: 1,
                        mediaType: ['image', 'video'],
                        sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
                        sourceType: ['album'], //从相册选择
                        success: (res) => {
                            this.chooseImageSingle(res);
                        }
                    });
                } else {
                    this.$showModal({
                        content: '请选择图片或视频',
                        cancelColor: "#FFFEFA",
                        cancelBackgroundColor: "linear-gradient(0deg, #F65555 0%, #E54848 100%)",
                        confirmColor: "#FFFEFA",
                        confirmBackgroundColor: "linear-gradient(0deg, #F65555 0%, #E54848 100%)",
                        confirmText: '图片',
                        cancelText: '视频',
                        success: res => {
                            if (res.confirm) {
                                uni.chooseImage({
                                    count: 1,
                                    sourceType: ['album'], //从相册选择
                                    success: (res) => {
                                        uni.compressImage({
                                            src: res.tempFilePaths[0],
                                            quality: 75,
                                            success: (compResult) => {
                                                console.log("压缩成功", compResult);
                                                compResult.errMsg = res.errMsg;
                                                this.chooseImageSingle(compResult,
                                                    "image")
                                            },
                                            fail: (err) => {
                                                console.log("压缩失败", err);
                                            }
                                        });
                                    }
                                });
                            } else if (res.cancel) {
                                uni.chooseVideo({
                                    count: 1,
                                    sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
                                    sourceType: ['album'], //从相册选择
                                    success: (res) => {
                                        this.chooseImageSingle(res, "video")
                                    }
                                });
                            }
                        }
                    })
                }
            },
            chooseImageSingle(res, mediaType) {
                console.log("chooseResult", res);
                if (res.errMsg != "chooseMedia:ok" &&
                    res.errMsg != "chooseImage:ok" &&
                    res.errMsg != "chooseVideo:ok") {
                    uni.showToast({
                        title: "选择图片或视频发生了错误",
                        icon: "none"
                    })
                    return;
                }
                let tempFilePath = "";
                if (res.errMsg == "chooseMedia:ok") {
                    let response = res.tempFiles[0];
                    tempFilePath = response.tempFilePath;
                    mediaType = response.mediaType ?? response.fileType;
                }
                if (res.errMsg == "chooseImage:ok") {
                    tempFilePath = res.tempFilePath;
                }
                if (res.errMsg == "chooseVideo:ok") {
                    tempFilePath = res.tempFilePath;
                }
                this.uploadImage(tempFilePath, mediaType).then(filePath => {
                    console.log("上传结果", filePath);
                    if (mediaType == "video") {
                        console.log("上传视频");
                        this.formData.video = filePath;
                    } else if (mediaType == "image") {
                        console.log("上传图片");
                        this.formData.pic = filePath;
                    }
                });
            },
            uploadImage(tmpfile, mediaType) {
                uni.showLoading({
                    mask: true,
                    title: '上传中...',
                })

                return new Promise((resolve, reject) => {
                    this.$api.uploadImg(tmpfile, mediaType).then(res => {
                        uni.hideLoading();
                        resolve(res.data);
                    }).catch(err => {
                        console.log('上传失败', err);
                        uni.hideLoading();
                        reject("");
                    })
                })
            },
            viewImage(e) {
                uni.previewImage({
                    urls: this.imgList,
                    current: e.currentTarget.dataset.url
                });
            },
            delImg(e) {
                this.$showModal({
                    title: '美食家',
                    content: '确定要删除这段素材吗？',
                    cancelText: '桥豆麻袋',
                    confirmText: '走你',
                    success: res => {
                        if (res.confirm) {
                            this.formData.pic = "";
                            this.formData.video = "";
                        }
                    }
                })
            },

            chooseImageMultiple() {
                console.log("批量传图")

                uni.chooseImage({
                    count: 9,
                    sourceType: ['album'], //从相册选择
                    success: (res) => {
                        console.log("chooseResult", res);
                        if (res.errMsg != "chooseImage:ok") {
                            uni.showToast({
                                title: "选择图片或视频发生了错误",
                                icon: "none"
                            })
                            return;
                        }

                        res.tempFiles.forEach((response, index) => {

                            uni.compressImage({
                                src: response.path,
                                quality: 75,
                                success: (compResult) => {
                                    console.log("压缩成功", compResult);

                                    this.uploadImage(compResult.tempFilePath, "image")
                                        .then(tempFilepath => {
                                            console.log("上传结果", tempFilepath);
                                            this.formData.listStep.push({
                                                "description": "",
                                                "imageUrl": tempFilepath,
                                            })
                                        });
                                },
                                fail: (err) => {
                                    console.log("压缩失败", err);
                                }
                            });
                        })
                    }
                });
            },
            delStep(item) {
                var findIndex = this.formData.listStep.indexOf(item);
                if (findIndex == -1) {
                    this.formData.listStep.unshift(item);
                } else {
                    this.formData.listStep.splice(findIndex, 1);
                }
            },
            pickerChangeMonth(e) {
                this.indexMonth = e.detail.value;
                this.formData.listMonth = [{
                    "cateName": this.pickerMonth[this.indexMonth],
                    "type": 1
                }]
            },
            pickerChangeType(e) {
                this.indexType = e.detail.value;
                this.formData.listType = [{
                    "cateName": this.pickerType[this.indexType],
                    "type": 2
                }]
            },
            pickerChangeMake(e) {
                this.indexMake = e.detail.value;
                this.formData.listMake = [{
                    "cateName": this.pickerMake[this.indexMake],
                    "type": 3
                }]
            },
            pickerChangeUnit(e, index) {
                console.log("选择单位", e, JSON.stringify(this.formData.listMaterial));
                console.log(JSON.stringify(this.formData.listMaterial[index]));
                let item = this.formData.listMaterial[index];
                item.indexUnit = e.detail.value;
                item.unit = this.pickerUnit[item.indexUnit];
                this.formData.listMaterial[index] = item;
                console.log("选择单位=", JSON.stringify(item));
            },
            addMaterial(event) {
                console.log("入参", event);
                if (this.formData.listMaterial.filter(it => it.name == event).length > 0) {
                    uni.showToast({
                        title: event + "已存在列表中",
                        icon: "none"
                    })
                    return;
                }
                this.formData.listMaterial.push({
                    name: event,
                    quantity: "",
                    unit: "",
                    indexUnit: -1
                })
            },
            onAdd() {
                this.formData.listMaterial.push({
                    name: "",
                    quantity: "",
                    unit: "",
                    indexUnit: -1
                })
            },
            onEdit() {
                if (this.isEdit)
                    this.isEdit = false;
                else
                    this.isEdit = true;
            },
            onRemove(item) {
                var findIndex = this.formData.listMaterial.indexOf(item);
                if (findIndex == -1) {
                    this.formData.listMaterial.unshift(item);
                } else {
                    this.formData.listMaterial.splice(findIndex, 1);
                }
            },
            submit() {
                console.log("提交数据", this.formData);
                if (!this.validate()) return;

                uni.showLoading({
                    mask: true,
                    title: '发布中...',
                })

                this.formData.auditStatus = 0;
                this.$api.saveBook(this.formData).then((res) => {
                    console.log("提交结果", res)

                    uni.hideLoading();
                    this.$showModal({
                        content: '发布菜谱成功',
                        confirmText: "确定",
                        showCancel: false,
                        success: (res) => {
                            if (res.confirm) {
                                uni.navigateBack({
                                    delta: 1
                                });
                            }
                        }
                    });
                }).catch((err) => {
                    uni.hideLoading();
                    console.error('request fail', err);
                    uni.showToast({
                        title: "发布失败",
                        icon: "none"
                    })
                })
            },
            validate() {
                if (!this.formData.pic && !this.formData.video) {
                    uni.showToast({
                        title: "封面图或视频不能为空",
                        icon: "none"
                    })
                    return false;
                }
                if (this.formData.listMonth.length == 0) {
                    uni.showToast({
                        title: "月龄不能为空",
                        icon: "none"
                    })
                    return false;
                }
                if (this.formData.listMaterial.length == 0) {
                    uni.showToast({
                        title: "食材用料不能为空",
                        icon: "none"
                    })
                    return false;
                }
                if (this.formData.listMaterial.filter(it => it.name.trim() == "" || it.unit == "").length > 0) {
                    uni.showToast({
                        title: "食材用料或单位不能为空",
                        icon: "none"
                    })
                    return false;
                }

                if (this.formData.listStep.length == 0) {
                    uni.showToast({
                        title: "做法步骤不能为空",
                        icon: "none"
                    })
                    return false;
                }
                if (this.formData.listStep.filter(it => it.description.trim() == "").length > 0) {
                    uni.showToast({
                        title: "步骤描述不能为空",
                        icon: "none"
                    })
                    return false;
                }
                return true;
            },
            onBackPress(options) {
                console.log("onBackPress");

                //避免死循环
                if (options.from === 'navigateBack') return false;
                //自己的判断条件，执行自定义的返回操作
                if (this.customClosePage()) {
                    //你的自定义操作
                    console.log("终止返回，进行提示");
                }
                //执行uniapp的返回操作
                else uni.navigateBack()

                //返回true表示我要自定义onBackPress
                return true
            }
        }
    }
</script>

<style>
    .text-xl-important {
        font-size: 24px !important;
    }

    .text-tips-main {
        font-size: 26px;
        position: absolute;
        color: #8799a3;
        margin: auto;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
        font-size: 30upx !important;
    }

    .text-tips-sub {
        font-size: 26px;
        position: absolute;
        color: #8799a3;
        margin: auto;
        bottom: 0;
        left: 0;
        right: 0;
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
        font-size: 28upx !important;
        top: 130upx !important;
    }

    .tag-close {
        position: absolute;
        right: 0;
        top: 0;
        border-bottom-left-radius: 3px;
        padding: 3px 6px;
        height: auto;
        background-color: rgba(0, 0, 0, 0.5);
        font-size: 12px;
        vertical-align: middle;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        box-sizing: border-box;
        font-family: Helvetica Neue, Helvetica, sans-serif;
        white-space: nowrap;
        color: white;
        z-index: 9999;
    }

    .text-sm-black {
        font-size: 12px !important;
        color: #000000 !important;
    }
</style>
